package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    //注入实现spring提供的repository对象
    private StrategyCommentMongoRepository repository;

    @Override
    public void save(StrategyComment comment) {
        comment.setCreateTime(new Date());
        repository.save(comment);
    }

    @Override
    public Page findByDetailId(StrategyCommentQuery qo) {
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize());
        return repository.findByDetailId(qo.getDetailId(), pageable);
    }

    @Override
    public void commentThumbUp(Long fromId, String toId) {
        Optional<StrategyComment> op = repository.findById(toId);
        op.ifPresent(comment -> {
            List<Long> thumbuplist = comment.getThumbuplist();
            if (thumbuplist.contains(fromId)) {
                //取消点赞
                thumbuplist.remove(fromId);
            }else {
                //点赞
                thumbuplist.add(fromId);
            }
            //设置点赞数
            comment.setThumbupnum(thumbuplist.size());
            //重新覆盖此评论
            repository.save(comment);
        });
    }
}
